//
//  ViewController.swift
//  JKLivingBeautyCamera
//
//  Created by 王冲 on 2020/8/4.
//  Copyright © 2020 王冲. All rights reserved.
//

import UIKit
import GPUImage
import AVKit

let livingBeautyViewH: CGFloat = 250
class ViewController: UIViewController {

    /// 美颜设置界面
    lazy var livingBeautyView: JKLivingBeautyView = {
        let beautyView = JKLivingBeautyView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height, width: UIScreen.main.bounds.size.width, height: livingBeautyViewH))
        beautyView.backgroundColor = UIColor.black.withAlphaComponent(0.47)
        return beautyView
    }()
    
    // MARK: 懒加载属性
    // 创建视频源
    fileprivate lazy var camera : GPUImageVideoCamera? = GPUImageVideoCamera(sessionPreset: AVCaptureSession.Preset.high.rawValue, cameraPosition: .front)
    // 创建预览图层
    fileprivate lazy var preview : GPUImageView = GPUImageView(frame: self.view.bounds)
    
    // 初始化滤镜
    let bilateralFilter = GPUImageBilateralFilter() // 磨皮
    let exposureFilter = GPUImageExposureFilter() // 曝光
    let brightnessFilter = GPUImageBrightnessFilter() // 美白
    let satureationFilter = GPUImageSaturationFilter() // 饱和
    
    // 创建写入对象
    fileprivate lazy var movieWriter : GPUImageMovieWriter = { [unowned self] in
        // 创建写入对象
        let writer = GPUImageMovieWriter(movieURL: self.fileURL, size: self.view.bounds.size)
        // 设置写入对象的属性
        return writer!
    }()
    
    // MARK: 计算属性
    var fileURL : URL {
        return URL(fileURLWithPath: "\(NSTemporaryDirectory())123.mp4")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        print(fileURL)
        initUI()
        setLiving()
    }
    
    func setLiving() {
        // 1.设置camera方向
        // 竖屏
        camera?.outputImageOrientation = .portrait
        // 前置
        camera?.horizontallyMirrorFrontFacingCamera = true
        // 2.创建预览的View
        view.insertSubview(preview, at: 0)
        // 3.获取滤镜组
        let filterGroup = getGroupFilters()
        // 4.设置GPUImage的响应链
        camera?.addTarget(filterGroup)
        filterGroup.addTarget(preview)
        // 5.开始采集视频
        camera?.startCapture()
        // 6.设置writer的属性
        // 是否对视频进行编码
//        movieWriter.encodingLiveVideo = true
//        // 将writer设置成滤镜的target
//        filterGroup.addTarget(movieWriter)
//        // 设置camera的编码
//        camera?.delegate = self
//        camera?.audioEncodingTarget = movieWriter
//
//        DispatchQueue.global().async {
//            self.movieWriter.startRecording()
//        }
    }
    
    fileprivate func getGroupFilters() -> GPUImageFilterGroup {
        // 1.创建滤镜组（用于存放各种滤镜：美白、磨皮等等）
        let filterGroup = GPUImageFilterGroup()
        
        // 2.创建滤镜(设置滤镜的引来关系)
        bilateralFilter.addTarget(brightnessFilter)
        brightnessFilter.addTarget(exposureFilter)
        exposureFilter.addTarget(satureationFilter)
        
        // 3.设置滤镜组链初始&终点的filter
        filterGroup.initialFilters = [bilateralFilter]
        filterGroup.terminalFilter = satureationFilter
        
        return filterGroup
    }
    
    // MARK:- UI布局
    func initUI() {
        
        livingBeautyView.beautySetingBlock = { [weak self] (type, value) in
            guard let weakSelf = self else {
                return
            }
            switch type {
            case 1:
                // - 10 ~ 10
                print("磨皮：\(value)")
                weakSelf.bilateralFilter.distanceNormalizationFactor = CGFloat(value) * 8
            case 2:
                print("曝光：\(value)")
                weakSelf.exposureFilter.exposure = CGFloat(value) * 20 - 10
            case 3:
                print("美白：\(value)")
                weakSelf.brightnessFilter.brightness = CGFloat(value) * 2 - 1
            case 4:
                print("饱和：\(value)")
                weakSelf.satureationFilter.saturation = CGFloat(value * 2)
            default:
                print("")
            }
        }
        livingBeautyView.beautyCameraBlock = { [weak self] (isOn) in
            guard let weakSelf = self else {
                return
            }
            if isOn {
                weakSelf.camera?.removeAllTargets()
                let group = weakSelf.getGroupFilters()
                weakSelf.camera?.addTarget(group)
                group.addTarget(weakSelf.preview)
            } else {
                weakSelf.camera?.removeAllTargets()
                weakSelf.camera?.addTarget(weakSelf.preview)
            }
        }
            
        view.addSubview(livingBeautyView)
    
    }
    
    // MARK:- 美颜设置
    /// 美颜设置
    @IBAction func beautySetingClick(_ sender: UIButton) {
        
        sender.isSelected = !sender.isSelected
        UIView.animate(withDuration: 0.25) {
            self.livingBeautyView.frame.origin.y = sender.isSelected ? UIScreen.main.bounds.size.height - livingBeautyViewH : UIScreen.main.bounds.size.height
        }
    
    }
    
    // MARK:- 切换摄像头
    /// 切换摄像头
    @IBAction func switchCamera(_ sender: Any) {
        camera?.rotateCamera()
    }
    
    // MARK:- 结束直播
    /// 结束直播
    @IBAction func endLivingCllick(_ sender: Any) {
    
        camera?.stopCapture()
        preview.removeFromSuperview()
        movieWriter.finishRecording()
    }
    
    // MARK:- 播放视频
    /// 播放视频
    @IBAction func playVideoClick(_ sender: Any) {
        print(fileURL)
        let playerVc = AVPlayerViewController()
        playerVc.player = AVPlayer(url: fileURL)
        present(playerVc, animated: true, completion: nil)
    }
    
}

extension ViewController : GPUImageVideoCameraDelegate {
    func willOutputSampleBuffer(_ sampleBuffer: CMSampleBuffer!) {
        print("采集到画面")
    }
}
